import os
from event_bus import EventBus
from plugin_interface import PluginInterface
from json_plugin import JSONPlugin
from language_plugin import LanguagePlugin

class PluginManager:
    """插件管理器"""
    def __init__(self):
        self.plugins = []
        self.event_bus = EventBus()
    
    def load_plugins(self, plugins_dir):
        """加载插件目录中的所有插件"""
        if not os.path.exists(plugins_dir):
            return
        
        self.plugins = []
        
        # 加载语言插件
        language_plugin = LanguagePlugin()
        self.plugins.append(language_plugin)
        
        # 加载JSON插件
        for item in os.listdir(plugins_dir):
            if item.endswith('.json') and not item.endswith('.disabled'):
                item_path = os.path.join(plugins_dir, item)
                self._load_plugin(item_path)
    
    def _load_plugin(self, config_path):
        """加载单个插件"""
        try:
            plugin = JSONPlugin(config_path)
            self.plugins.append(plugin)
            print(f"插件已加载: {config_path}")
        except Exception as e:
            print(f"加载插件失败: {config_path}, 错误: {str(e)}")
    
    def initialize_plugins(self, app):
        """初始化所有插件"""
        for plugin in self.plugins:
            try:
                plugin.initialize(app)
            except Exception as e:
                print(f"初始化插件失败: {getattr(plugin, 'config_path', '未知')}, 错误: {str(e)}")
    
    def publish_event(self, event_type, *args, **kwargs):
        """发布事件到所有插件"""
        self.event_bus.publish(event_type, *args, **kwargs)
    
    def on_ui_ready(self):
        """UI就绪后通知所有插件"""
        for plugin in self.plugins:
            try:
                if hasattr(plugin, 'on_ui_ready') and callable(plugin.on_ui_ready):
                    plugin.on_ui_ready()
            except Exception as e:
                print(f"UI就绪通知插件失败: {getattr(plugin, 'config_path', '未知')}, 错误: {str(e)}")
